package org.web.demo.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author yexi
 */
@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取要下载的文件名称，响应回去
        String fileName = req.getParameter("fileName");
        // 获取浏览器类型
        String header = req.getHeader("User-Agent");
        // 根据浏览器类型设置文件下载的名称(区分IE与非IE)
        // 原因: http的header规定要求其内容必须为iso-8859-1编码
        String name = header.contains("MSIE") ? URLEncoder.encode(fileName,
                "UTF-8") : new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        //设置下载文件名称
        resp.addHeader("Content-Disposition", "attachment;filename=" + name);
        // 获取文件所在根路径
        String realPath = this.getServletContext().getRealPath("/WEB-INF/download");
        // 使用工具类 Files 的 copy 方法获取文件输入流，再借助响应对象的输出流把文件响应回浏览器
        Files.copy(Paths.get(realPath, fileName), resp.getOutputStream());
    }
}